"""
    Views to allow you to do stuff with squadrons
"""
from django.http import Http404, HttpResponseRedirect

from badmin.models import Squadron
from badmin.forms import SquadronForm

from badmin.views.helpers import respond

def list(request):
  # # Testing code to populate the data store
  # new_sqn = Squadron(number='2386')
  # new_sqn.put()
  sqn_list = Squadron.all().fetch(1000)
  template_values = {
    'instance_list': sqn_list,
  }
  return respond(request, 'badmin/squadron/list.html', template_values)
  
def new(request):
  if request.method == 'POST':
    form = SquadronForm(request.POST)
    if form.is_valid():
      sqn = Squadron(**form.cleaned_data)
      sqn.put()
      return HttpResponseRedirect(sqn.view_url())
  else:
    form = SquadronForm()
  template_values = {
    'form': form,
  }
  return respond(request, 'badmin/squadron/new.html', template_values)

def view(request, number):
  sqn = Squadron.get_by_number(number)
  if not sqn:
    raise Http404
  template_values = {
    'instance': sqn,
  }
  return respond(request, 'badmin/squadron/view.html', template_values)

def edit(request, number):
  """docstring for edit"""
  sqn = Squadron.get_by_number(number)
  if not sqn:
    raise Http404
  
  if request.method == 'POST':
    form = SquadronForm(request.POST)
    if form.is_valid():
      for key, value in form.cleaned_data.items():
        setattr(sqn, key, value)
      sqn.put()
      return HttpResponseRedirect(sqn.view_url())
  else:
    form = SquadronForm(initial={'number':sqn.number})
  
  template_values = {
    'instance': sqn,
    'form': form,
  }
  return respond(request, 'badmin/squadron/edit.html', template_values)

def delete(request, number):
  sqn = Squadron.get_by_number(number)
  if not sqn:
    raise Http404
  if request.method == 'POST':
    sqn.delete()
    return HttpResponseRedirect(sqn.list_url())
  
  template_values = {
    'instance': sqn,
  }
  return respond(request, 'badmin/squadron/delete.html', template_values)